/**
 * @author Franco Ponticelli
 */

package js;
import js.Dom;

class UA {
	public static var isGecko(default, null) : Bool;
	public static var gecko(default, null) : Float;
	public static var isIe(default, null) : Bool;
	public static var ie(default, null) : Float;
	public static var isOpera(default, null) : Bool;
	public static var opera(default, null) : Float;
	public static var isWebkit(default, null) : Bool;
	public static var webkit(default, null) : Float;
	public static var isMobile(default, null) : Bool;
	public static var mobile(default, null) : String;
	public static var isAir(default, null) : Bool;
	public static var isCaja(default, null) : Bool;
	public static var caja(default, null) : Float;
	public static var isSecure(default, null) : Bool;
	public static var os(default, null) : String;
	
	static var _ = init();
	static function init() {
		isGecko = isIe = isOpera = isWebkit = isMobile = isAir = isCaja = isSecure = false;
		gecko = ie = opera = webkit = caja = 0.0;
		
		var nav : Navigator = untyped navigator;
		var ua = null;
		if (nav != null)
			ua = nav.userAgent;
		var loc = Lib.window.location;
		var href = null;
		if (loc != null)
			href = loc.href;
		isSecure = href != null && href.toLowerCase().indexOf("https") == 0;
		
		if (ua == null) return;
		
		if ((~/windows|win32/).match(ua)) {
			os = 'windows';
		} else if ((~/windows|win32/).match(ua)) {
			os = 'macintosh';
		}
		
		isWebkit = (~/KHTML/).match(ua);
		var re = ~/AppleWebKit\/([^\s]*)/;
		isMobile = false;
		if (re.match(ua) && re.matched(1) != null) {
			webkit = Std.parseFloat(re.matched(1));
			if ((~/ Mobile\//).match(ua)) {
				mobile = "Apple"; // iPhone or iPod Touch
				isMobile = true;
			} else {
				re = ~/NokiaN[^\/]*/;
				if (re.match(ua)) {
					mobile = re.matched(0); // Nokia N-series, ex: NokiaN95
					isMobile = true;
				}
			}
			
			re = ~/AdobeAIR\/([^\s]*)/;
			if (re.match(ua)) {
				isAir = true;
			}
		}
		
		if (!isWebkit) { // not webkit
			// @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr)
			re = ~/Opera[\s\/]([^\s]*)/;
			if (re.match(ua) && re.matched(1) != null) {
				isOpera = true;
				opera = Std.parseFloat(re.matched(1));
				re = ~/Opera Mini[^;]*/;
				if (re.match(ua)) {
					isMobile = true;
					mobile = re.matched(0); // ex: Opera Mini/2.0.4509/1316
				}
			} else { // not opera or webkit
				re = ~/MSIE\s([^;]*)/;
				if (re.match(ua) && re.matched(1) != null) {
					isIe = true;
					ie = Std.parseFloat(re.matched(1));
				} else { // not opera, webkit, or ie
					re = ~/Gecko\/([^\s]*)/;
					if (re.match(ua)) {
						isGecko = true;
						re = ~/rv:([^\s\)]*)/;
						if (re.match(ua) && re.matched(1) != null) {
							gecko = Std.parseFloat(re.matched(1));
						}
					}
				}
			}
		}
	}
}